﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace SuperKit {
    class CogUdpClient {
        private string ip;
        private UdpClient udpcSend;
        private string serverIp;
        private int serverPort;
        private bool isStart = false;
        private bool isOnce = false;

        public CogUdpClient(string ip,string serverIp, int serverPort) {
            this.ip = ip;
            this.serverIp = serverIp;
            this.serverPort = serverPort;
        }

        public static string IpAddress {
            get {
                string hostName = Dns.GetHostName();
#pragma warning disable CS0618 // 类型或成员已过时
                IPHostEntry localhost = Dns.GetHostByName(hostName);
#pragma warning restore CS0618 // 类型或成员已过时
                IPAddress localaddr = localhost.AddressList[0];
                return localaddr.ToString();
            }
        }
        static public int UDPClientPort => ConfigReader.Instance.GetInt("UDPClientPort");
        static public int UDPServerPort => ConfigReader.Instance.GetInt("UDPServerPort");

        static public void SendLocal(string msg) {
            var client = new CogUdpClient(IpAddress,IpAddress, UDPServerPort);
            client.isOnce = true;
            client.Start();
            client.Send(msg);
        }

        public void Start() {
            if (isStart) return;

            // 本机IP，指定的端口号
            udpcSend = GetLocalIpep();

            isStart = true;
        }

        private UdpClient GetLocalIpep() {
            int point = 0;
            while (point < 10000) {
                try {
                    IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(ip), NetworkKit.GetFreePort());
                    var udpcSend = new UdpClient(endPoint);
                    return udpcSend;
                } catch (SocketException) {
                    continue;
                }                
            }
            return null;
        }

        public void Close() {
            if (isStart == false) return;

            udpcSend.Close();

            isStart = false;
        }

        public void Send(String msg) {
            if (isStart == false) {
                //Messenger.Error("Udp client is not ready!");
                return;
            }
            Thread thrSend = new Thread(OnSendMessage);
            thrSend.Start(msg);
        }

        private void OnSendMessage(object obj) {
            string message = (string)obj;
            byte[] sendbytes = Encoding.UTF8.GetBytes(message);

            // 发送到的IP地址和端口号（这里使用同一种）
            IPEndPoint remoteIpep = new IPEndPoint(IPAddress.Parse(serverIp), serverPort);

            udpcSend.Send(sendbytes, sendbytes.Length, remoteIpep);

            if (isOnce) {
                Close();
            }
        }
    }
}
